package com.cotasul.converter;

import javax.faces.application.FacesMessage;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import javax.faces.convert.FacesConverter;

import com.cotasul.bean.FornecedorBean;
import com.cotasul.negocio.FornecedorServico;

@FacesConverter(forClass = FornecedorBean.class, value = "fornecedorConverter")
public class FornecedorConverter implements Converter {

	private FornecedorServico<FornecedorBean> fornecedorServico;

	public FornecedorConverter() {
		fornecedorServico = new FornecedorServico<FornecedorBean>();
	}

	public Object getAsObject(FacesContext facesContext, UIComponent component,
			String submittedValue) {
		if (submittedValue.trim().equals("")) {
			return null;
		} else {
			try {
				long number = Long.parseLong(submittedValue);
				return fornecedorServico.filtraFornecedores(new FornecedorBean(
						null, number)).get(0);

			} catch (Exception exception) {
				exception.printStackTrace();
				throw new ConverterException(new FacesMessage(
						FacesMessage.SEVERITY_ERROR, "Conversion Error",
						"Not a valid player"));
			}
		}
	}

	public String getAsString(FacesContext facesContext, UIComponent component,
			Object value) {
		if (value == null || value.equals("")) {
			return "";
		} else {
			return String.valueOf(((FornecedorBean) value).getCodigo());
		}
	}
}
